// 列表项在数据库中怎么存储的？比如 省，市，县...
// 树状菜单 场景题

const sourceList = [
    {
        id: 1,
        name: '中国',
        parentId: 0,
    },
    {
        id: 2,
        name: '北京',
        parentId: 1,
    },
    {
        id: 3,
        name: '上海',
        parentId: 1,
    },
    {
        id: 4,
        name: '东城区',
        parentId: 2,
    },
    {
        id: 5,
        name: '西城区',
        parentId: 2,
    },
]

function listToTree(list, parentId) {
    const tree = [];
    for (const item of list) {
        if (item.parentId === parentId) {
            const children = listToTree(list, item.id);
            if (children.length > 0) {
                item.children = children;
            }
            tree.push(item);
        }
    }
    return tree;
}

const tree = listToTree(sourceList, 0);
console.log(tree);